package net.bblbs.zhongrx;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import net.bblbs.zhongrx.util.HttpRequest;

import org.json.JSONObject;


/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "ZRX_LOGIN_ACTIVITY";
    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;

    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        sp = this.getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);

        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        String email = sp.getString("email","");
        mEmailView.setText(email);

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
//                int i = EditorInfo.IME_ACTION_DONE;
                //记住用户名
                sp = getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);
                String email = mEmailView.getText().toString();
                if (!email.equals("")){
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("email", email);
                    editor.commit();
                }

                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });



        Button mEmailSignInButton = (Button) findViewById(R.id.sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                //记住用户名
                sp = getSharedPreferences(getString(R.string.shared_preferences_file_name), Context.MODE_PRIVATE);
                String email = mEmailView.getText().toString();
                if (!email.equals("")){
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("email", email);
                    editor.commit();
                }
                //登录
                attemptLogin();
            }

        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

        String password = sp.getString("password","");
        if(!TextUtils.isEmpty(password)){
            mAuthTask = new UserLoginTask(email, password);
            mAuthTask.execute((Void) null);
        }

    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String email = mEmailView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            mAuthTask = new UserLoginTask(email, password);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {

        private final String mEmail;
        private final String mPassword;

        UserLoginTask(String email, String password) {
            mEmail = email;
            mPassword = password;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.
            try {
                JSONObject jObj = new JSONObject();
                jObj.put("email", mEmail);
                jObj.put("password", mPassword);

                String loginResultJSON = HttpRequest.post(getString(R.string.ws_base_url), getString(R.string.ws_login_path), jObj.toString());
                Log.d(TAG, "loginResultJSON: " +loginResultJSON);

//                OkHttpClient client = new HttpUtil().getInstance();

//                OkHttpClient client = new OkHttpClient();

//                MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//                Log.d(TAG, "jObj: "+ jObj.toString());
//                RequestBody body = RequestBody.create(JSON, jObj.toString());
//                RequestBody formBody = new FormBody.Builder()
//                        .add("email", mEmail)
//                        .add("password", mPassword)
//                        .build();
//
//                Request request = new Request.Builder()
//                        .url(getString(R.string.ws_base_url) + getString(R.string.ws_login_path))
//                        .post(formBody)
//                        .build();
//
//                Response response = null;
//                try {
//                     response = client.newCall(request).execute();
//
//                    // Do something with the response.
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }

//                Log.d(TAG, "loginResultJSON: " + response.body().string());
//                String loginResultJSON = response.body().toString();

//                Log.d(TAG, "get headerName : "+ HttpRequest.getTokenParam(getString(R.string.ws_base_url)).get("headerName"));
//                Log.d(TAG, "get token : "+ HttpRequest.getTokenParam(getString(R.string.ws_base_url)).get("token"));
//
//                client.newCall(new Request.Builder().url(getString(R.string.ws_base_url)+ "/tango//listPhase1Records/10/0").build()).enqueue(new Callback() {
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
//                        String responseText = response.body().string();
//                        Log.d(TAG, "responseText: " + responseText);
//                    }
//
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        // 通过runOnUiThread()方法回到主线程处理逻辑
//                        Log.d(TAG, "error: " + e.toString());
//                    }
//                });


//                String getPhaseJSON = HttpRequest.get(getString(R.string.ws_base_url), "/tango/listPhase1Records/10/0");
//                Log.d(TAG, "getPhaseJSON: " +getPhaseJSON);

                if (loginResultJSON != null && loginResultJSON.contains("login passed"))
                    return true;
            } catch (Exception e) {
                Log.e(TAG, "err: " + e.toString());
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                //调用uiHandler
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("password", mPassword);
                editor.commit();

                Message msg = new Message();
                uiHandler.sendMessage(msg);
                finish();
            } else {
                if (NetworkStatus.isNetworkAvailable(getBaseContext()))
                    mPasswordView.setError(getString(R.string.error_incorrect_password));
                else
                    mPasswordView.setError(getString(R.string.error_network_not_available));

                mPasswordView.requestFocus();
            }
        }

        private Handler uiHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                // Activity跳转
                Intent intent = new Intent(LoginActivity.this, SelectActivity.class);
                startActivity(intent);
            }
        };


        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

